package com.qfedu.edu.exception;

import com.qfedu.edu.observer.notify.base.Subject;
import com.qfedu.edu.result.R;
import com.qfedu.edu.result.ResponseCode;
import com.qfedu.edu.utils.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.sql.SQLException;

@ControllerAdvice
@Slf4j
public class GlobalException {
    @Autowired
    private Subject subject;

    @ExceptionHandler(BusinessException.class)
    public ModelAndView handlerException(BusinessException e) {
        log.info("出现业务异常", e.getMessage());

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/toErrorPage");
        modelAndView.addObject("message", e.getMessage());
        modelAndView.addObject("code", e.getCode());
        return modelAndView;
    }

    @ExceptionHandler(SQLException.class)
    public R handlerException(SQLException e) {
        log.info("出现sql异常", e.getMessage());
        R error = R.error(ResponseCode.SQL_ERROR);
        return error;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R handlerException(Exception e) {
        log.error("系统发生异常:{}", e.getMessage());
        //通知运维
        //可能存在高并发问题，使用线程池做缓存
        ThreadPoolUtils.getNotifyThreadPool().execute(() -> {
            subject.notifyList(e.getMessage());
        });
        return R.error(ResponseCode.SYS_ERROR);
    }
}
